//use "cnpm install" to install all dependencies
const express = require('express')
const app = express()
const port = 6543
const fs = require('fs')
const path = require('path')
const JSON5 = require('json5')
const jwt = require('jsonwebtoken')
var Mysql = require('./mysql') //导入自己编写的数据库操作模块
var MYSQL = new Mysql();
var PRIVITE_KEY = 'secret';
// getJsonFile方法定义了如何读取json文件并解析成数据对象
function getJsonFile(filePath) {
    // 读取指定json文件
    var json = fs.readFileSync(path.resolve(__dirname, filePath), 'utf-8');
    // 解析并返回
    return JSON5.parse(json);
}
// 使用cors
const cors = require('cors')
app.use(
    cors({
        origin: ['http://localhost:8080', 'http://chengyubbs.51vip.biz'], //前端地址
        methods: ['GET', 'POST', 'DELETE', 'PUT'],
        alloweHeaders: ['Conten-Type', 'authorization']
    })
)

//测试API
app.get('/testserver', (req, res) => res.send('Hello World!'))

//API 1.1.1
app.post('/login', function (req, res) {
    //console.log("testing..");
    var post = '';

    // 定义了一个post变量，用于暂存请求体的信息
    // 通过req的data事件监听函数，每当接受到请求体的数据，就累加到post变量中
    req.on('data', function (chunk) {
        post += chunk;
    });
    // 在end事件触发后，通过querystring.parse将post解析为真正的POST请求格式，然后向客户端返回。
    req.on('end', function () {
        // post = querystring.parse(post);
        var rev = JSON5.parse(post);
        MYSQL.findoneuser(rev, res);
    });

    // 每次相应请求时读取mock data的json文件
    // getJsonFile方法定义了如何读取json文件并解析成数据对象
    // var json = getJsonFile('./userInfo.json5');
    // // 将json传入Mock.mock方法中，生成的数据返回给浏览器
    // res.json();

})

//API 1.1.2
app.post('/users', function (req, res) {
    var post = '';

    // 定义了一个post变量，用于暂存请求体的信息
    // 通过req的data事件监听函数，每当接受到请求体的数据，就累加到post变量中
    req.on('data', function (chunk) {
        post += chunk;
    });
    // 在end事件触发后，通过querystring.parse将post解析为真正的POST请求格式，然后向客户端返回。
    req.on('end', function () {
        // post = querystring.parse(post);
        var rev = JSON5.parse(post);
        //MYSQL.findoneuser(rev,res);
        MYSQL.adduser(rev, res);
    });
})

//API 1.2.1
app.get('/questionnaire', function (req, res) {
    // 每次相应请求时读取模板json文件
    var pagenum = req.query.pagenum;
    var pagesize = req.query.pagesize;
    var typ = req.query.type;
    var token = req.headers.authorization;
    if (token && token != '') {
        jwt.verify(token, PRIVITE_KEY, function (err, decoded) {
            if (err) {
                return res.json({ success: false, message: 'token信息错误.' });
            }
            else {
                MYSQL.findquestionnaire(decoded, pagenum, pagesize, typ, res);
            }
        });
    }
    else {
        //测试独立服务器
        console.log("testing..");
        res.json('{"msg":"no token!"}');
        return;
    }
    // var json = getJsonFile('./questionnaire.json5');
    //res.json(Mock.mock(json));
})

//API 1.2.2
app.delete('/questionnaire', function (req, res) {
    var post = '';
    req.on('data', chunk => {
        post += chunk;
    });
    req.on('end', function () {
        var rev = JSON5.parse(post);
        var idstodel = rev.questionnaireid;
        var deltype = rev.type;
        var token = req.headers.authorization;
        if (token && token != '') {
            jwt.verify(token, PRIVITE_KEY, function (err, decoded) {
                if (err) {
                    return res.json({ success: false, message: 'token信息错误.' });
                }
                else {
                    console.log('deleting q ids: ', idstodel);
                    MYSQL.delquestionnaire(idstodel, deltype, res);
                    console.log('del finished');
                }
            });
        }
        else {
            //no token
        }
    })
})

//API 1.2.3
app.get('/add', function (req, res) {
    var token = req.headers.authorization;
    if (token && token != '') {
        jwt.verify(token, PRIVITE_KEY, function (err, decoded) {
            if (err) {
                return res.json({ success: false, message: 'token信息错误.' });
            }
            else {
                MYSQL.addexam(decoded.name, res);
            }
        });
    }
    else {
        //no token
    }

})

//API 1.2.4
app.post('/save', function (req, res) {
    var post = '';
    req.on('data', chunk => {
        post += chunk;
    });
    req.on('end', function () {
        var rev = JSON5.parse(post);
        var token = req.headers.authorization;
        if (token && token != '') {
            jwt.verify(token, PRIVITE_KEY, function (err, decoded) {
                if (err) {
                    return res.json({ success: false, message: 'token信息错误.' });
                }
                else {
                    console.log("rev: ", rev);
                    var json = getJsonFile('./save.json5');
                    MYSQL.saveexam(rev, res);
                }
            });
        }
        else {
            //no token
        }
    })
})

//API 1.2.5
app.put('/release', function (req, res) {
    var post = '';
    req.on('data', chunk => {
        post += chunk;
    });
    req.on('end', function () {
        var rev = JSON5.parse(post);
        var questionnaireid = rev.questionnaireid;
        var token = req.headers.authorization;
        if (token && token != '') {
            jwt.verify(token, PRIVITE_KEY, function (err, decoded) {
                if (err) {
                    return res.json({ success: false, message: 'token信息错误.' });
                }
                else {
                    console.log("asking for: ", questionnaireid);
                    MYSQL.releaseques(questionnaireid, res);
                }
            });
        }
        else {
            //no token
        }
    })
})

//API1.2.6
app.post('/edit', function (req, res) {
    var post = '';
    req.on('data', chunk => {
        post += chunk;
    });
    req.on('end', function () {
        var rev = JSON5.parse(post);
        var questionnaireid = rev.questionnaireid;
        var token = req.headers.authorization;
        if (token && token != '') {
            jwt.verify(token, PRIVITE_KEY, function (err, decoded) {
                if (err) {
                    return res.json({ success: false, message: 'token信息错误.' });
                }
                else {
                    console.log("edit, id: ", questionnaireid);
                    MYSQL.editques(questionnaireid, res);
                }
            });
        }
        else {
            //no token
        }
    })
})

//API 1.3.1
app.get('/fillin', function (req, res) {
    var questionnaireid = req.query.questionnaireid;
    console.log("fillin, id: ", questionnaireid);
    //和edit调用相同函方法
    MYSQL.editques(questionnaireid, res);
})

//API 1.3.2
app.post('/submit', function (req, res) {
    var post = '';
    req.on('data', chunk => {
        post += chunk;
    });
    req.on('end', function () {
        var rev = JSON5.parse(post);
        console.log(rev);
        MYSQL.submitexam(rev, res);
    })
})

//API 1.4.1
app.post('/data', function (req, res) {
    var post = '';
    req.on('data', chunk => {
        post += chunk;
    });
    req.on('end', function () {
        var data = JSON5.parse(post);
        var token = req.headers.authorization;
        var qid = data.questionnaireid;
        if (token && token != '') {
            jwt.verify(token, PRIVITE_KEY, function (err) {
                if (err) {
                    return res.json({ success: false, message: 'token信息错误.' });
                }
                else {
                    MYSQL.getQuesData(qid, res);
                }
            });
        }
        else {
            //no token
        }
    })
})

//API 1.5.1
app.post('/recover', function (req, res) {
    var post = '';
    req.on('data', chunk => {
        post += chunk;
    });
    req.on('end', function () {
        var rev = JSON5.parse(post);
        var questionnaireid = rev.questionnaireid;
        var token = req.headers.authorization;
        if (token && token != '') {
            jwt.verify(token, PRIVITE_KEY, function (err, decoded) {
                if (err) {
                    return res.json({ success: false, message: 'token信息错误.' });
                }
                else {
                    console.log("recover, id: ", questionnaireid);
                    MYSQL.recover(questionnaireid, res);
                }
            });
        }
        else {
            //no token
        }
    })
})

//开始监听端口
app.listen(port, () => console.log(`App listening on port ${port}!`))